/*
 * BLLib.Xml.XmlFile
 * Andy Tidball
 * 
 * Project: Black Lightning General Library
 * Copyright: GNU General Public License
 */

using System;
using System.IO;
using System.Xml;

namespace BLLib.Xml {
	/// <summary>
	/// Represents an XML file.
	/// </summary>
	public class XmlFile {
		// member data
		private XmlTag _RootTag = null; // the file's root tag

		/// <summary>
		/// Creates a new XML file with the given root tag.
		/// </summary>
		public XmlFile(XmlTag RootTag) {
			_RootTag = RootTag;
		}

		/// <summary>
		/// Loads an XML file from the given filename.
		/// </summary>
		/// <param name="Filename">The name of the file to load from.</param>
		/// <remarks>
		/// This constructor won't catch any underlying file IO exceptions, the caller will have to do that.
		/// For their reference, the StreamReader constructor which takes one string is used to open the file.
		/// </remarks>
		public XmlFile(string Filename) {
			// open up the file
			XmlTextReader XmlStream = new XmlTextReader(new StreamReader(Filename));

			// read through the file
			while (XmlStream.Read()) {
				// keep going until we find the first element
				if (XmlStream.NodeType != XmlNodeType.Element) {
					continue;
				}

				// read that in as the root element
				_RootTag = new XmlTag(XmlStream);
			}

			// close the file
			XmlStream.Close();
		}

		/// <summary>
		/// The tag that encompasses the entire XML file.
		/// </summary>
		public XmlTag RootTag {
			get {
				return _RootTag;
			}
		}

		/// <summary>
		/// Saves the XML file to the given filename.
		/// </summary>
		/// <param name="Filename">The name of the file to save to.</param>
		/// <remarks>
		/// This constructor won't catch any underlying file IO exceptions, the caller will have to do that.
		/// For their reference, the StreamWriter constructor which takes one string is used to open the file.
		/// </remarks>
		public void Save(string Filename) {
			// create the output stream
			XmlTextWriter XmlStream = new XmlTextWriter(new StreamWriter(Filename));

			// setup the formatter
			XmlStream.Formatting = Formatting.Indented;
			XmlStream.IndentChar = '\t';
			XmlStream.Indentation = 1;

			// start the document
			XmlStream.WriteStartDocument();

			// save the root tag to the document
			_RootTag.Save(XmlStream);

			// close the document
			XmlStream.Close();
		}
	}
}
